import random
from time import sleep
import json
import os
import sys
import time
import requests
from openpyxl import load_workbook
from collections import defaultdict
from datetime import datetime, date
from datetime import timedelta



def json_exists(file_path):
    """
    检查指定路径的JSON文件是否存在。
    :param file_path: JSON文件的路径
    :return: 如果文件存在返回True，否则返回False
    """
    return os.path.exists(file_path)

#查rating
def get_rating(handle):
    # Codeforces API URL for user info
    url = f"https://codeforces.com/api/user.info?handles={handle}"

    try:
        # 发送请求
        response = requests.get(url, timeout=10)  # 设置超时时间
        response.raise_for_status()  # 如果响应状态码不是200，将抛出异常

        # 解析JSON数据
        data = response.json()
        # 检查返回状态是否OK
        if data['status'] == 'OK' and data['result']:
            # 获取用户信息
            user_info = data['result'][0]  # 只有一个用户信息
            # 提取rating
            rating = user_info.get('rating')

            return rating,user_info.get('maxRating')
        else:
            return "Failed to retrieve data: " + data.get('comment', 'Unknown error')

    except requests.exceptions.HTTPError as http_err:
        return f"HTTP error occurred: {http_err}"
    except requests.exceptions.RequestException as e:
        return f"Request failed: {e}"
    except ValueError:
        return "Failed to parse JSON response"


#创建并读写json文件
def read_or_create_json(file_path, default_data):
    """
    读取JSON文件，如果文件不存在，则创建一个包含默认数据的新JSON文件。
    :param file_path: JSON文件的路径
    :param default_data: 如果文件不存在，用于创建新文件的默认数据
    :return: JSON文件中的数据
    """
    # 检查文件是否存在
    if os.path.exists(file_path):
        # 文件存在，读取文件
        with open(file_path, 'r', encoding='utf-8') as file:
            data = json.load(file)

    else:
        # 文件不存在，创建新文件并写入默认数据
        with open(file_path, 'w', encoding='utf-8') as file:
            json.dump(default_data, file, indent=4, ensure_ascii=False)
        # 读取新创建的文件
        with open(file_path, 'r', encoding='utf-8') as file:
            data = json.load(file)
    return data

#查解题数量
def get_solved(handle):
    # Codeforces API URL for user submissions
    url = f"https://codeforces.com/api/user.status?handle={handle}"

    # 发送请求
    response = requests.get(url)

    # 检查请求是否成功
    if response.status_code == 200:
        # 解析JSON数据
        data = response.json()
        # print(data)
        # 检查返回状态是否OK
        if data['status'] == 'OK':
            submissions = data['result']
            problem_stats = defaultdict(int)

            # 遍历提交记录，统计每个问题的出现次数
            for submission in submissions:
                problem = submission['problem']
                problem_id = f"{problem['index']}. {problem['name']}"  # 组合问题编号和名称
                verdict = submission['verdict']
                if verdict == 'OK':
                    problem_stats[problem_id] += 1


            return dict(problem_stats)
        else:
            return "Failed to retrieve data: " + data.get('comment', 'Unknown error')

    else:
        return f"Request failed with status code {response.status_code}"

# all_data = []

# 获取当前日期
today = date.today()

# 加载工作簿
wb = load_workbook('cf ID.xlsx')
# 选择工作表
ws = wb['Sheet1']
fd = {}
# 读取数据
for row in ws.iter_rows(values_only=True):
    # sleep(random.randint(2,4))
    print(row[0],row[1])
    handle = row[1]#input("输入查询id")
    problem_stats = get_solved(handle)
    rating,maxrating = get_rating(handle)
    if isinstance(problem_stats, dict):
        # print("Problem Statistics:",end="")
        cnt = 0
        for problem, count in problem_stats.items():
            cnt += 1
            # print(f"Problem {problem}: {count} times solved")
        print("今天的日期是：", today)
    #     print("solve "+str(cnt)+" problems")
    # print(f"The current rating of {handle} is: {rating},the max is {maxrating}")

    dic = {}
    dic['name'] = row[0];
    dic['id'] = handle
    dic['maxrating'] = maxrating
    dic['rating'] = rating
    dic['all-solved'] = cnt
    # all_data.append(dic)
    lastday = today - timedelta(days=1)
    file_path = f'{lastday}.json'
    if json_exists(file_path):
        default = {}
        data = read_or_create_json(file_path, default)
        if row[0] not in data:
            dic['today-solved'] = 0
        else :
            dic['today-solved'] = abs(int(data[row[0]]['all-solved'])-cnt)
    else :
        dic['today-solved'] = 0
    fd[row[0]]=dic


file_path = f'{today}.json'

default_data = fd  # 你可以根据需要设置默认数据
data = read_or_create_json(file_path, default_data)
# print(data)
print("finish")





# all_data.sort(key=lambda x:x['rating'])
#
# # 定义要写入文件的内容
# content = all_data
#
# # 指定文件名
# file_name = f"{today} rankings.txt"
#
# # 使用with语句打开文件，确保文件在操作后正确关闭
# with open(file_name, 'w', encoding='utf-8') as file:
#     # 写入内容到文件
#     file.write(content)
#
# print(f"文件 '{file_name}' 已创建并写入内容。")

#
# # TXT文件的读写，没写好，先开坑，以后再填
# file_path = f'{today}.txt'
# with open('rankings.txt', 'w',  encoding='utf-8') as file:
#     c = file.read()
#     a = c.split("\n")
#     for i in a:
#         info = i.split(" ")
#         print(info)
#         name = info[0]
#         solve = info[1]
#         rating = info[2]
#         time = info[3]
#         ID = info[4]

